//
//  ComplaintView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/27/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit


protocol ComplaintViewDelegate {
    func gotError (error: RequestError)
    func closeComplaintView ()
}

final class ComplaintView: UIView {
    
    enum ComplaintType: String, CaseIterable {
        case is_spam = "Спам"
        case is_inappropriate_content = "Не сответствующий контент"
        case is_fake_information = "Фейк"
    }
    
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        lbl.textColor = .black
        lbl.textAlignment = .left
        lbl.sizeToFit()
        lbl.text = "Пожаловаться"
        return lbl
    }()
    
    private lazy var messageView: UITextView = {
        let textView = UITextView ()
        textView.backgroundColor = .lightBlueColor
        textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 12, right: 8)
        textView.font = .systemFont(ofSize: 16)
        textView.textColor = .darkBlueColor
        textView.layer.cornerRadius = 15
        textView.text = placeholder
        textView.delegate = self
        return textView
    }()
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "dismiss"), for: .normal)
        btn.addTarget(self, action: #selector(closeView), for: .touchUpInside)
        return btn
    }()
    
    private lazy var readyBtn: UIButton = {
        let btn = UIButton()
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 8
        btn.backgroundColor = .blueColor
        btn.setTitleColor(.white, for: .normal)
        btn.setTitle("Готово", for: .normal)
        btn.alpha = 0.6
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(sendComplaint), for: .touchUpInside)
        return btn
    }()
    
    private lazy var itemsStack: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .fill
        stackView.distribution = .fillProportionally
        return stackView
    }()
    
    private var spinnerView = SpinnerView()
    
    // MARK: - Props
    
    private var selectedItem: ComplaintType? {
        didSet {
            if selectedItem == nil {
                readyBtn.alpha = 0.6
                readyBtn.isEnabled = false
            } else {
                readyBtn.alpha = 1
                readyBtn.isEnabled = true
            }
        }
    }
    
    public var delegate: ComplaintViewDelegate!
    
    private let data = ComplaintType.allCases
    private let placeholder = "Поясните жалобу"
    private var advertID: Int!
    
    private var isLoading: Bool = false {
        didSet {
            self.isUserInteractionEnabled = !isLoading
            isLoading ? spinnerView.startAnimating() : spinnerView.stopAnimating()
            self.backgroundColor = isLoading ? UIColor(red: 0.4, green: 4, blue: 4, alpha: 1) : .white
        }
    }
    
    
    @objc private func closeView () {
        delegate.closeComplaintView()
    }
    
    override init(frame: CGRect) {
        super.init(frame: .zero)
        self.addViews()
        self.addItems()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func setAdvertId (_ id: Int) {
        self.advertID = id
    }
    
    private func addViews () {
        
        self.backgroundColor = .white
        
        self.addSubview(titleLbl)
        self.addSubview(closeBtn)
        self.addSubview(itemsStack)
        self.addSubview(readyBtn)
        self.addSubview(messageView)
        self.addSubview(spinnerView)
        
        self.closeBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().inset(28)
            make.width.height.equalTo(16)
            make.trailing.equalToSuperview().offset(-16)
        }
        self.titleLbl.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalTo(closeBtn)
        }
        self.messageView.snp.makeConstraints { (make) in
            make.height.equalTo(80)
            make.top.equalTo(titleLbl.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        self.itemsStack.snp.makeConstraints { (make) in
            make.bottom.equalTo(readyBtn.snp.top).offset(-12)
            make.top.equalTo(messageView.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview()
        }
        self.readyBtn.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-12)
            make.height.equalTo(44)
        }
        self.spinnerView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
    }
    
    private func addItems () {
        
        _ = itemsStack.arrangedSubviews.map {
            itemsStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        for (i, el) in ComplaintType.allCases.enumerated() {
            let item = self.createItem(title: el.rawValue, i: i)
            item.backgroundColor = .white
            
            let gesture = GestureWithTag(target: self, action: #selector(onSelectItem(sender:)))
            gesture.tag = i
            
            item.addGestureRecognizer(gesture)
            itemsStack.addArrangedSubview(item)
        }
    }
    
    @objc private func onSelectItem (sender: GestureWithTag) {
        self.selectedItem = data[sender.tag]
        self.updateSelection()
    }
    
    private func updateSelection () {
        if self.selectedItem != nil {
            _ = itemsStack.arrangedSubviews.map {
                if data[$0.tag] == self.selectedItem {
                    $0.backgroundColor = .lightBlueColor
                } else {
                    $0.backgroundColor = .white
                }
            }
        }
    }
    
    private func createItem (title:String, i: Int) -> UIView {
        let _view = UIView()
        _view.tag = i
        
        let titleLbl = UILabel()
        titleLbl.font = .systemFont(ofSize: 15)
        titleLbl.textColor = .darkBlueColor
        titleLbl.text = title
        titleLbl.tag = 1
        _view.addSubview(titleLbl)
        
        if i == 0 {
            //let _ = Divider(parent: view)
        }
        
        titleLbl.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        _view.snp.makeConstraints { (make) in
            make.height.equalTo(48)
        }
        
        return _view
    }
}

// MARK: - Network

extension ComplaintView {
    
    private func createRequest () -> URLRequest {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/complaints/"))
        request.httpMethod = "POST"
        
        let text = self.messageView.text == placeholder ? "" : self.messageView.text
        let ids = [ComplaintType.is_fake_information: "is_fake_information", .is_spam: "is_spam", .is_inappropriate_content: "is_inappropriate_content"]
        let complaintField = ids[self.selectedItem!]
        
        let body = [
            "advert": self.advertID as Any,
            "description": text as Any,
            complaintField: true
        ] as [String? : Any]
        
        if let bodyJSON = try? JSONSerialization.data(withJSONObject: body, options: []) {
            request.httpBody = bodyJSON
        }
        
        return request
    }
    
    @objc private func sendComplaint () {
        self.isLoading = true
        
        Backend().fetchFromBackend(for: Bool.self, request: self.createRequest(), statusCode: 201, sendBool: true) { (result) in
            self.isLoading = false
            switch result {
            case .failure(let err):
                self.delegate.gotError(error: err)
            case .success(_):
                self.delegate.closeComplaintView()
            }
        }
    }
}


extension ComplaintView: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == placeholder {
            textView.text = ""
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text == "" {
            textView.text = placeholder
        }
    }
}
